import json
import os
import re

from django import http
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils.timezone import now
from django.views import View
from django_redis import get_redis_connection

import constants
from apps.company.models import Company
from apps.resume.models import UserResume
from apps.resume.utils import query_resume
from apps.users.models import User
from lagouwang.settings import STATICFILES_DIRS


class RegisterView(View):
    def get(self, request):
        return render(request, './login/register.html')

    def post(self, request):
        json_data = json.loads(request.body.decode())
        mobile = json_data.get('mobile')
        password = json_data.get('password')
        sms_code = json_data.get('smscode')
        username = mobile

        # 校验参数
        if not all([mobile, password, sms_code]):
            return http.HttpResponse('请填写完整信息')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': constants.MOBILEERROR, 'errmsg': '手机号输入不正确'})

        if not re.match(r'[a-zA-Z0-9.]{6,16}', password):
            return http.JsonResponse({'errno': constants.PASSWORDERROR, 'errmsg': '密码输入格式错误'})

        # 查询当前手机号是否被注册
        count = User.objects.filter(mobile=mobile).count()
        print(count)
        if count >= 1:
            return http.JsonResponse({'errno': constants.MOBILEREPETITION, 'errmsg': '当前手机号已被注册'})

        # 校验短信验证码
        redis_conn = get_redis_connection('code')
        sms_code_saved = redis_conn.get('sms_%s' % mobile)
        if sms_code_saved is None:
            return http.JsonResponse({'errno': constants.MOBILEREPETITION, 'errmsg': '无效的短信验证码'})
        if sms_code != sms_code_saved.decode():
            return http.JsonResponse({'errno': constants.MOBILEREPETITION, 'errmsg': '输入的短信验证码有误'})

        # 写入数据库
        try:
            user = User.objects.create_user(username=username, mobile=mobile, password=password)
        except:
            return http.JsonResponse({'errno': constants.USERERROR, 'errmsg': '注册失败'})

        login(request, user)
        # 定义一个响应对象
        response = http.JsonResponse({'errno': constants.OK, 'errmsg': '注册成功'})
        # 在响应对象中设置cookie值为用户名
        response.set_cookie('username', username)

        # 返回响应对象
        return response


class LoginView(View):
    def get(self, request):
        return render(request, './login/login.html')

    def post(self, request):
        json_data = json.loads(request.body.decode())
        mobile = json_data.get('mobile')
        password = json_data.get('password')
        print(mobile)
        print(password)
        # 校验参数
        if not all([mobile, password]):
            return http.HttpResponse('请填写完整信息')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': constants.MOBILEERROR, 'errmsg': '手机号输入不正确'})

        if not re.match(r'[a-zA-Z0-9.]{6,16}', password):
            return http.JsonResponse({'errno': constants.PASSWORDERROR, 'errmsg': '密码输入格式错误'})

        # 检查是否有该用户
        user = authenticate(username=mobile, password=password)
        if not user:
            return http.JsonResponse({'errno': constants.USERERROR, 'errmsg': '手机号或密码错误'})

        response = http.JsonResponse({'errno': constants.OK, 'errmsg': '登录成功'})
        login(request, user)
        response.set_cookie('username', user.username)

        return response


class LogoutView(View):
    """
    退出
    """

    @staticmethod
    def get(request):
        #
        logout(request)

        response = redirect(reverse('index:index'))

        response.delete_cookie('username')

        return response


class ForgetPwdView(View):
    """忘记密码"""

    def get(self, request):
        return render(request, "login/forget.html")

    def post(self, request):
        json_data = json.loads(request.body.decode())
        mobile = json_data.get("mobile")
        image_code_text = json_data.get("image_code_text")
        uuid = json_data.get("uuid")

        if not all([mobile, image_code_text]):
            return http.JsonResponse({'errno': constants.INFO_MISSING, "errmsg": "请填写完整信息"})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': constants.MOBILEERROR, 'errmsg': '手机号输入不正确'})

        # 判断该用户是否存在数据库
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return http.JsonResponse({'errno': constants.MOBILEERROR, "errmsg": "该用户不存在"})

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('code')
        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.JsonResponse({'code': constants.IMAGECODEERR, 'errmsg': '图形验证码失效'})
        # 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            print(e)

        # 对比图形验证码
        image_code_server = image_code_server.decode()  # bytes转字符串
        if image_code_text.lower() != image_code_server.lower():  # 转小写后比较
            return http.JsonResponse({'code': constants.IMAGECODEERR, 'errmsg': '输入图形验证码有误'})

        response = http.JsonResponse({"errno": constants.OK, "errmsg": "OK"})

        response.set_cookie("verifications_mobile", mobile, max_age=constants.MOBILE_REDIS_EXPIRES)

        return response


class ForgetPwd2View(View):
    """忘记密码第2步"""

    def get(self, request):
        mobile = request.COOKIES.get("verifications_mobile")
        print("mobile", mobile)

        if not mobile:
            return render(request, "common/404.html")
        context = {
            "mobile": mobile
        }

        # 返回第二页并清除cookie
        response = render(request, "login/forget-2.html", context)

        return response

    def post(self, request):
        json_data = json.loads(request.body.decode())
        sms_code = json_data.get("sms_code")
        print(sms_code)
        mobile = request.COOKIES.get("verifications_mobile")
        # 校验短信验证码
        redis_conn = get_redis_connection('code')
        sms_code_saved = redis_conn.get('sms_%s' % mobile)
        if sms_code_saved is None:
            return http.JsonResponse({'errno': constants.MOBILEREPETITION, 'errmsg': '无效的短信验证码'})
        if sms_code != sms_code_saved.decode():
            return http.JsonResponse({'errno': constants.MOBILEREPETITION, 'errmsg': '输入的短信验证码有误'})

        response = http.JsonResponse({'errno': constants.OK, "errmsg": "OK"})

        return response


class ForgetPwd3View(View):
    """忘记密码第3步"""

    def get(self, request):
        return render(request, "login/forget-3.html")

    def post(self, request):
        mobile = request.COOKIES.get("verifications_mobile")
        json_data = json.loads(request.body.decode())
        new_password = json_data.get("new_password")
        new_password2 = json_data.get("new_password2")
        if not all([mobile, new_password, new_password2]):
            return http.JsonResponse({"errno": constants.INFO_MISSING, 'errmsg': '请输入密码'})

        if new_password != new_password2:
            return http.JsonResponse({'errno': constants.PASSWORDERROR, 'errmsg': '两次密码输入不一致'})

        try:
            user = User.objects.get(mobile=mobile)
            # 设置新密码
            user.set_password(new_password)
            user.save()

        except:
            return http.JsonResponse({"errno": constants.DBERROR, 'errmsg': '修改密码失败，请稍后再试'})

        response = http.JsonResponse({'errno': constants.OK, 'errmsg': '修改成功,请重新登录'})
        response.delete_cookie("verifications_mobile")
        return response


class UserSettingView(LoginRequiredMixin, View):
    """邮箱QQ绑定"""

    def get(self, request):
        user = request.user
        context = {
            "user": user
        }
        return render(request, 'accountBind.html', context)


class UserSettingTWOView(LoginRequiredMixin, View):
    """修改密码"""

    def get(self, request):
        user = request.user

        # 查询该用户有没有公司
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            company = None

        context = {
            'user': user,  # 用户
            "company": company,  # 用户作品展示
        }

        return render(request, 'updatePwd.html', context)

    def post(self, request):
        old_password = request.POST.get('oldpassword')
        new_password = request.POST.get('newpassword')
        new_password2 = request.POST.get('comfirmpassword')

        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({"errno": constants.INFO_MISSING, 'errmsg': '请输入密码'})

        if new_password != new_password2:
            return http.JsonResponse({'errno': constants.PASSWORDERROR, 'errmsg': '两次密码输入不一致'})

        try:
            # 获取当前用户对象
            user = User.objects.get(id=request.user.id)
            # 校验密码
            if not (user and user.check_password(old_password)):
                return http.JsonResponse({"errno": constants.INFO_MISSING, 'errmsg': '原密码输入有误'})
            # 设置新密码
            user.set_password(new_password)
            user.save()

        except:
            return http.JsonResponse({"errno": constants.DBERROR, 'errmsg': '修改密码失败，请稍后再试'})
        # 退出登录
        logout(request)
        response = http.JsonResponse({'errno': constants.OK, 'errmsg': '修改成功,请重新登录'})
        response.delete_cookie('username')
        return response
